package edu.scut.luluteam.contextlib.collection;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

import edu.scut.luluteam.contextlib.ContextClient;

/**
 * 监听推送的Msg的阅读情况
 *
 * @author Guan
 * @date Created on 2018/12/4
 */
public class MsgLifecycleCallback implements Application.ActivityLifecycleCallbacks {

    private static String TAG = "MsgLifecycleCallback";

    /**
     * key : 阅读该Msg的activity.getClass().getName()
     * value:timestamp
     */
    private static ConcurrentHashMap<String, Long> map = new ConcurrentHashMap<>();


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        String messageId = activity.getIntent().getStringExtra("messageId");
        if (StringUtils.isNotEmpty(messageId)) {
            Log.i(TAG, "在map中添加messageId=" + messageId);
            map.put(messageId, System.currentTimeMillis());
        }

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        //如果Activity中带有messageId字段，则表示是一个展示Message的Activity
        String messageId = activity.getIntent().getStringExtra("messageId");
        if (StringUtils.isNotEmpty(messageId) && map.containsKey(messageId)) {
            long duration = System.currentTimeMillis() - map.get(messageId);
            int wordCount = activity.getIntent().getIntExtra("wordCount", -1);
            Log.i(TAG, "messageId: " + messageId + " 阅读时间：" + duration);

            ContextClient.rating(messageId, -1, duration, wordCount);

        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
    }


}
